package com.longrise.android.byjk.plugins.course.coursedetail.healthrisk.catalogue;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.google.gson.Gson;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.plugins.course.coursedetail.healthrisk.HealthRiskActivity;
import com.longrise.android.byjk.plugins.course.coursedetail.healthrisk.bean.RiskCourseBean;
import com.longrise.android.byjk.plugins.course.coursedetail.healthrisk.event.RiskIntroEvent;
import com.longrise.android.byjk.plugins.course.coursedetail.healthrisk.event.RiskRefreshEvent;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.common.base.BaseFragment;
import com.longrise.common.utils.AppUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by callxkj on 2018/1/14.
 * 风险管理师的 目录
 */

public class HealthRiskCatalogueFragment extends BaseFragment<HealthRiskCataloguePresenter>
        implements HealthRiskCatalogueContract.View {

    private RecyclerView mRcv;
    private String mCourseid;
    private HealthRiskCatalogueAdapter mAdapter;
    private LinearLayoutManager mLinearLayoutManager;
    public int mSelectPosition;


    public static HealthRiskCatalogueFragment getInstance(String courseid) {
        HealthRiskCatalogueFragment fragment = new HealthRiskCatalogueFragment();
        Bundle bundle = new Bundle();
        bundle.putString("courseid", courseid);
        fragment.setArguments(bundle);
        return fragment;
    }

    private void getIntentData() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            mCourseid = arguments.getString("courseid");
        }
    }


    @Override
    protected int getLayoutResourse(@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_healthrisk_catalogue;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        mRcv = (RecyclerView) mRootView.findViewById(R.id.healthrisk_catalogue_fragment_irv);
        getIntentData();
        initRcv();
        initData();
        initEvent();
    }

    private void initRcv() {
        mAdapter = new HealthRiskCatalogueAdapter(null);
        mRcv.setAdapter(mAdapter);
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        mRcv.setLayoutManager(mLinearLayoutManager);
        mAdapter.expandAll();
    }


    private void initData() {
        mPresenter.toGetCourseData(mCourseid, true);
    }


    private void initEvent() {
        mAdapter.setOnCourseItemClickListener(new HealthRiskCatalogueAdapter.CourseItemClickListener() {
            @Override
            public void onClick(VideoParams videoParams) {
                ((HealthRiskActivity) getActivity()).checkNetWorkAndtoStudy(videoParams);
            }
        });

        mAdapter.setOnCourseLastSelectListener(new HealthRiskCatalogueAdapter.OnCourseLastSelectListener() {


            @Override
            public void onSelect(int position) {

                mSelectPosition = position;
            }
        });
    }


    @Override
    public void showLoadingDialog() {

    }

    @Override
    public void dismissLoadingDialog() {

    }

    /**
     * 获取课程数据
     *
     * @param isfirst        是否是第一次初始化请求
     * @param latelystudy    头部上次学习的课程
     * @param catelogs       目录数据
     * @param studentno      学号
     * @param totaltraintime 课程总学时
     */
    @Override
    public void setCourseData(boolean isfirst, EntityBean latelystudy, EntityBean[] catelogs, String studentno, double totaltraintime) {
        ((HealthRiskActivity) getActivity()).setTopCourseData(latelystudy, catelogs, studentno);

        //介绍页面的学时
        RiskIntroEvent event = new RiskIntroEvent();
        event.setTotaltraintime(totaltraintime);
        EventBus.getDefault().post(event);

        Gson gson = new Gson();
        String lastLearnCwid = null;
        String lateplan = latelystudy.getString("lateplan");
        try {
            RiskCourseBean riskCourseBeantop = gson.fromJson(lateplan, RiskCourseBean.class);
            lastLearnCwid = riskCourseBeantop.getCurnode().getCwid();
        } catch (Exception e) {
            e.printStackTrace();
        }


        //---解析目录数据
        List<MultiItemEntity> beans = new ArrayList<>();
        if (catelogs != null) {
            for (int x = 0; x < catelogs.length; x++) {
                CatalogueParentItem item0 = new CatalogueParentItem();
                EntityBean catelog = catelogs[x];
                String name = catelog.getString("name");
                item0.setName(name);
                EntityBean[] nextmulus = catelog.getBeans("nextmulu");
                if (nextmulus != null) {
                    for (int y = 0; y < nextmulus.length; y++) {
                        EntityBean nextmulu = nextmulus[y];
                        Integer iscw1 = nextmulu.getInt("iscw");
                        if (iscw1 == 0) {
                            Integer title2 = nextmulu.getInt("title");
                            if (title2 == 2) {  //课程的二级标题
                                CatalogueChildItem1 item1 = new CatalogueChildItem1();
                                item1.setName(nextmulu.getString("name"));
                                item0.addSubItem(item1);
                            } else if (title2 == 3) {  //课程的三级标题
                                CatalogueChildItem2 item2 = new CatalogueChildItem2();
                                item2.setName(nextmulu.getString("name"));
                                item0.addSubItem(item2);
                            }
                        } else if (iscw1 == 1) {  //代表课程的数据
                            String course = nextmulu.getString("course");
                            RiskCourseBean riskCourseBean = gson.fromJson(course, RiskCourseBean.class);
                            CatalogueChildItemVideo itemVideo = new CatalogueChildItemVideo();
                            itemVideo.setRiskCourseBean(riskCourseBean);
                            itemVideo.setCourseid(mCourseid);
                            itemVideo.setStudentno(studentno);
                            itemVideo.setLastlearnCwid(lastLearnCwid);
                            item0.addSubItem(itemVideo);
                        }

                    }

                }
                beans.add(item0);
            }
            mAdapter.setDatas(beans, isfirst);
            mAdapter.expandAll();
            dismissDefaultView();
            if (!isfirst) {
                mLinearLayoutManager.scrollToPosition(mSelectPosition);
            }
        }
    }

    /**
     * 显示网络错误页面
     */
    @Override
    public void showNetErrorPage() {
        HealthRiskActivity activity = (HealthRiskActivity) getActivity();
        if (activity != null) {
            activity.showNetErrorPage();
        }
    }

    /**
     * 隐藏默认页面 显示正常页面
     */
    public void dismissDefaultView() {
        HealthRiskActivity activity = (HealthRiskActivity) getActivity();
        if (activity != null) {
            activity.dismissDefaultView();
        }
        showNotice();
    }

    /**
     * 判断是否显示notice
     */
    private void showNotice() {
        int fxglsNotice = Control.getFxglsNotice();
        if (fxglsNotice == 1) {
            View v = View.inflate(AppUtil.getContext(), R.layout.toast_fxgls, null);
            Toast toast = new Toast(AppUtil.getContext());
            toast.setGravity(Gravity.BOTTOM | Gravity.FILL_HORIZONTAL, 0, 0);
            toast.setView(v);
            toast.setDuration(Toast.LENGTH_LONG);
            toast.show();
            Control.setFxglsNotice(0);
        }
    }

    /**
     * 视频播放页面退出刷新
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getRiskRefresh(RiskRefreshEvent event) {
        if (event.isNeedRefreshCatalogue()) {
            refresh();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 刷新
     */
    public void refresh() {
        mPresenter.toGetCourseData(mCourseid, false);
    }

}
